<template>
  <div class="blog-comment-edit card-item">
    <div class="comment-title">
      <el-input v-model="blogComment.name"
                :maxlength="10" show-word-limit
                placeholder="请输入昵称"/>
      <el-input v-model="blogComment.website"
                :maxlength="50" show-word-limit
                placeholder="请输入个人博客网站"/>
    </div>

    <el-input v-model="blogComment.content"
              placeholder="有什么想和我说的呢" :maxlength="500"
              :rows="7" show-word-limit type="textarea"
    />

    <div class="comment-button">
      <el-popover ref="emojiPopoverRef" placement="top" :width="300" trigger="hover">
        <template #default>
          <div class="emoji-panel">
            <EmojiPicker :native="true" @select="onSelectEmoji" />
          </div>
        </template>
        <template #reference>
          <el-button circle>
            <i class="fa-regular fa-face-smile"></i>
          </el-button>
        </template>
      </el-popover>

      <el-button type="primary"
                 :disabled="blogComment.content.length === 0"
                 @click="sendCommentClick"
                 class="send-button">发送</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import EmojiPicker from 'vue3-emoji-picker'
import 'vue3-emoji-picker/css'
import { defineProps, ref, onMounted } from 'vue'
import { useBlogStore } from '@/store/blog.ts'
import { deepCopyObject } from 'vue3-common/utils/dataUtil'
import { IBlogComment } from '@/types/blog.ts'

const blogStore = useBlogStore()
const emojiPopoverRef = ref()

const props = defineProps({
  parentId: {
    required: true,
    type: Number,
    default: 0
  }
})

const blogComment = ref<IBlogComment>({
  id: 0,
  blogId: 0,
  name: '',
  website: '',
  content: '',
  ipAddress: '',
  userAgent: '',
  parentId: 0,
  isApproved: true,
  createTime: ''
})

onMounted(() => {
  blogComment.value = deepCopyObject(blogStore.getEmptyBlogComment())
})

const onSelectEmoji = (emoji) => {
  if (blogComment.value.content.length <= 498) {
    blogComment.value.content += emoji.i
  }

  emojiPopoverRef.value.hide()
}

const sendCommentClick = async () => {
  blogComment.value.parentId = props.parentId

  if (!blogComment.value.name) {
    blogComment.value.name = 'Anonymous'
  }

  await blogStore.addBlogComment(blogStore.currentBlogId, blogComment.value)
  blogComment.value = deepCopyObject(blogStore.getEmptyBlogComment())
  blogStore.isShowCommentEdit = false
}
</script>

<style lang="scss">
.blog-comment-edit {
  width: 100%;
  padding: 10px;

  display: flex;
  flex-direction: column;
  gap: 10px;

  .comment-title {
    display: flex;
    justify-content: space-between;
    gap: 10px;
  }

  .comment-button {
    width: 100%;
    display: flex;

    .send-button {
      margin-left: auto;
    }
  }
}
</style>
